import React, { Component } from "react";
import { Row, Col, Card, Tabs, Input, Select, Spin, Divider } from "antd";
import { connect } from "dva";
import moment from "moment";
import numeral from "numeral";
import { Pie, TimelineChart } from "../../../components/Charts";
import NumberInfo from "../../../components/NumberInfo";
import DateComponent from "../../../components/dateComponent";
import { getTimeDistance } from "../../../utils/utils";
import EmptyPie from "../../../assets/empty-pie.png";

import styles from "./index.less";

const { TabPane } = Tabs;
const { Search } = Input;
const { Option } = Select;
const dafaultDate = getTimeDistance("date", 15);

@connect(({ feedback, home, user: { department } }) => ({
  feedbackData: feedback,
  homeData: home,
  department
}))
class FeedBackPage extends Component {
  state = {
    loading: false,
    currentTabKey: "1",
    sceneFuzzyName: "",
    select: "",
    deptCode: "",
    startDate: dafaultDate[0]
      ? moment(dafaultDate[0]).format("YYYY-MM-DD 00:00:00")
      : "",
    endDate: dafaultDate[0]
      ? moment(dafaultDate[1]).format("YYYY-MM-DD 23:59:59")
      : "",
    mode: "date"
  };

  componentDidMount() {
    const { department } = this.props;
    this.setState(
      {
        deptCode: department
      },
      () => {
        if (department) {
          this.getInitData();
        }
      }
    );
  }

  componentDidUpdate(prevProps) {
    const { department } = this.props;
    if (prevProps.department !== department && department) {
      this.setState(
        {
          deptCode: department
        },
        () => {
          this.getInitData();
        }
      );
    }
  }

  getInitData = () => {
    const { dispatch } = this.props;
    const { deptCode } = this.state;
    if (!deptCode) return;
    dispatch({
      type: "home/fetchDepList",
      payload: { deptCode }
    });
    this.getSceneList();
  };

  getSceneList = () => {
    const { dispatch } = this.props;
    const { startDate, endDate, deptCode, sceneFuzzyName, mode } = this.state;
    if (!deptCode) return;
    this.setState({
      loading: true
    });
    const action = mode === "date" ? "fetchPushDaily" : "fetchPushMonthly";
    dispatch({
      type: "feedback/fetchSceneList",
      payload: {
        params: {
          startDate,
          endDate,
          sceneFuzzyName,
          deptCode,
          orderField: "comment_count",
          orderType: "desc",
          pageNum: 1,
          pageSize: 5
        },
        action
      }
    }).then((data = []) => {
      const currentTabKey = data[0] ? data[0].sceneTemplateId : null;
      this.setState({
        loading: false,
        currentTabKey
      });
    });
  };

  // 趋势分析  & 反馈详情
  getChartData = () => {
    const { dispatch } = this.props;
    const { currentTabKey, mode, startDate, endDate } = this.state;
    this.setState({
      loading: true
    });
    const params = {
      sceneId: currentTabKey,
      startDate,
      endDate
    };
    const action = mode === "date" ? "fetchPushDaily" : "fetchPushMonthly";
    Promise.all([
      dispatch({
        type: "feedback/fetchTrendData",
        payload: {
          params,
          action
        }
      }),
      dispatch({
        type: "feedback/fetchFeedBackData",
        payload: { sceneId: currentTabKey }
      }),
      dispatch({
        type: "feedback/fetchTopCount",
        payload: {
          sceneId: currentTabKey
        }
      })
    ]).then(() => {
      this.setState({
        loading: false
      });
    });
  };

  handleTabChange = key => {
    this.emptyData();
    this.setState(
      {
        currentTabKey: key
      },
      () => {
        this.getChartData();
      }
    );
  };

  emptyData = () => {
    const { dispatch } = this.props;
    dispatch({
      type: "feedback/updateState",
      payload: { feedbackDetail: [], lineData: [], otherCount: {} }
    });
  };

  handleSearch = value => {
    this.setState(
      {
        sceneFuzzyName: value
      },
      () => {
        this.getSceneList();
      }
    );
  };

  handleSelect = value => {
    const { department } = this.props;
    const deptCode = value || department;
    this.setState(
      {
        deptCode
      },
      () => {
        this.getSceneList();
      }
    );
  };

  handleDateChange = (obj = {}) => {
    this.setState(
      {
        startDate: obj.date ? obj.date[0] : "",
        endDate: obj.date ? obj.date[1] : "",
        mode: obj.mode
      },
      () => {
        this.getSceneList();
      }
    );
  };

  render() {
    const { loading, currentTabKey, mode } = this.state;
    const {
      department,
      feedbackData = {},
      homeData: { pushDepList = [] }
    } = this.props;
    const {
      otherCount: {
        sendTotalCount = 0,
        readTotalCount = 0,
        commentTotalCount = 0
      } = {}
    } = feedbackData;
    let { sceneList = [], lineData = [], feedbackDetail = [] } = feedbackData;
    // sceneList = [
    //   {
    //     sceneTemplateId: 1,
    //     templateName: "场景一场景一场景一场景一场景一场景一场景一场景一",
    //     commentRate: "0.62"
    //   },
    //   { sceneTemplateId: 2, templateName: "场景二", commentRate: "0.8" },
    //   { sceneTemplateId: 3, templateName: "场景三", commentRate: "0.45" },
    //   { sceneTemplateId: 4, templateName: "场景四", commentRate: "0.75" },
    //   { sceneTemplateId: 5, templateName: "场景五", commentRate: "0.3" }
    // ];
    sceneList = sceneList.slice(0, 5);
    feedbackDetail = feedbackDetail.slice(0, 8);
    const CustomTab = ({ data = {}, currentTabKey: currentKey }) => (
      <Row gutter={8} style={{ width: 138, margin: "8px 0" }}>
        <Col span={24} className={styles.sceneTitle} title={data.templateName}>
          {data.templateName}
        </Col>
        <Col span={12}>
          <NumberInfo
            //  title={data.templateName}
            subTitle="反馈率"
            gap={2}
            total={
              data.commentRate ? `${Math.round(data.commentRate * 100)}%` : "0%"
            }
            theme={
              Number(currentKey) !== data.sceneTemplateId ? "light" : "active"
            }
          />
        </Col>
        <Col span={12}>
          <Pie
            animate={false}
            selected={false}
            color={Number(currentKey) !== data.sceneTemplateId && "#BDE4FF"}
            inner={0.55}
            tooltip={false}
            margin={[0, 0, 0, 0]}
            percent={
              data.commentRate && Math.round(data.commentRate * 100)
                ? Math.round(data.commentRate * 100)
                : "0"
            }
            height={64}
          />
        </Col>
      </Row>
    );
    lineData = lineData.map(item => ({
      x: item[`${mode}`],
      y1: `${Math.round(item.readRate * 100)}`,
      y2: `${Math.round(item.commentRate * 100)}`
    }));
    feedbackDetail = feedbackDetail.map(item => ({
      x: item.commentContent,
      y: item.useTimes
    }));
    return (
      <div className={styles.root}>
        <div className={styles.topSearch}>
          <div>
            <Search placeholder="请输入场景名称" onSearch={this.handleSearch} />
            <Select
              defaultValue={department}
              key={department}
              onChange={this.handleSelect}
              placeholder="请选择归属部门"
            >
              {pushDepList.length > 0 ? (
                pushDepList.map(({ orgId, orgCode, orgName }) => (
                  <Option key={`dep_${orgId}`} value={orgCode}>
                    {orgName}
                  </Option>
                ))
              ) : (
                <Option key="empty" disabled>
                  暂无数据！
                </Option>
              )}
            </Select>
          </div>
          <DateComponent onChange={obj => this.handleDateChange(obj)} />
        </div>
        <Spin spinning={loading}>
          <Card
            className={styles.offlineCard}
            bordered={false}
            bodyStyle={{ padding: "0 0 32px 0" }}
          >
            {sceneList.length > 0 ? (
              <Tabs
                activeKey={`${currentTabKey}`}
                onChange={this.handleTabChange}
              >
                {sceneList.map(item => (
                  <TabPane
                    tab={
                      <CustomTab data={item} currentTabKey={currentTabKey} />
                    }
                    key={item.sceneTemplateId}
                  >
                    <Row style={{ padding: "0 24px" }}>
                      <Col {...{ xs: 24, sm: 24, md: 24, lg: 12, xl: 14 }}>
                        <span className={styles.title}>趋势分析</span>

                        <TimelineChart
                          height={300}
                          data={lineData}
                          titleMap={{ y1: "查看率", y2: "反馈率" }}
                          key={currentTabKey}
                        />
                      </Col>
                      <Col
                        {...{ xs: 24, sm: 24, md: 24, lg: 12, xl: 10 }}
                        className={styles.feedbackWrap}
                      >
                        <span className={styles.title}>反馈详情</span>
                        <div className={styles.info}>
                          <span className={styles.item}>
                            <span>推送数量</span>
                            <span>{numeral(sendTotalCount).format("0,0")}</span>
                            <Divider type="vertical" />
                          </span>
                          <span className={styles.item}>
                            <span>查看数量</span>
                            <span>{numeral(readTotalCount).format("0,0")}</span>
                            <Divider type="vertical" />
                          </span>
                          <span className={styles.item}>
                            <span>反馈数量</span>
                            <span>
                              {numeral(commentTotalCount).format("0,0")}
                            </span>
                          </span>
                        </div>
                        {feedbackDetail.length > 0 ? (
                          <Pie
                            hasLegend
                            total
                            margin={[0, 0, 0, 0]}
                            height={260}
                            inner={0.75}
                            data={feedbackDetail}
                            percent={false}
                            // forceFit={false}
                            style={{
                              width: "100%",
                              minWidth: "460px",
                              paddingRight: "24px",
                              overflow: "hidden"
                            }}
                            key={currentTabKey}
                          />
                        ) : (
                          <div className={styles.emptyPie}>
                            <img src={EmptyPie} />
                            <span>暂无数据</span>
                            <h2>0</h2>
                          </div>
                        )}
                      </Col>
                    </Row>
                  </TabPane>
                ))}
              </Tabs>
            ) : (
              <p style={{ textAlign: "center", marginTop: "10px" }}>
                暂无数据！
              </p>
            )}
          </Card>
        </Spin>
      </div>
    );
  }
}

export default FeedBackPage;
